<template>
  <div class="front">
    <div class="front-text" style="width:190px;">第—步:扫码/手动输入货品条码</div>
    <el-row class="input-container" type="flex" justify="start" align="middle" >
      <el-col :span="2">
        <span class="label">货品条码：</span>
      </el-col>
      <el-col :span="4">
        <el-input v-model="inputValue" placeholder="请输入内容" class="input-box"></el-input>
      </el-col>
      <el-col :span="2">
        <el-button type="primary" @click="handleClick(inputValue)" class="submit-button">查询</el-button>
      </el-col>
    </el-row>
    <el-form :model="searchForm" v-if="isFormVisible" label-width="120px">
      <div class="front-text" style="width:270px;">第二步：选择需要调整的仓库以及填写调整数量</div>
      <el-row>
        <el-col :span="6">
          <el-form-item label="所属仓库" class="front-input" >
            <el-select v-model="searchForm.warehouseName" placeholder="搜索匹配" style="">
              <el-option v-for="item in warehouseList" :key="item" :label="isTemplate" :value="item" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="供应商" class="front-input">
            <el-select v-model="searchForm.storageName" placeholder="搜索匹配" style="" prop="supplierId">
              <el-option v-for="item in storageNameList" :key="item" :label="item" :value="item" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="账面在仓数" class="front-input">
            <el-input v-model="searchForm.oriNum" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="实际数量" class="front-input">
            <el-input v-model="searchForm.newNum" @change="updateAdjustedNum"/>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="调整数" class="front-input">
            <el-input :value="adjustedNum" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item>
            <el-button type="primary" @click="onSearch">添加到列表</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
  <div class="tail">
    <div class="tail-action">
      <el-button 
        type="primary" 
        plain
        icon="Plus"
        size="mini"
        :disabled="multiple"
        @click="dialogFormVisible = true"
      >生成调整单</el-button>
      <el-popover placement="bottom" trigger="click">
        <template #reference>
          <el-button><el-icon>
              <List />
            </el-icon>显示设置</el-button>
        </template>
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <el-checkbox-group v-model="selectedFilters" @change="handleCheckChange">
          <el-checkbox v-for="item in tableFilter.map(i => i.label)" :label="item" :key="item" />
        </el-checkbox-group>
      </el-popover>
    </div>
    <el-table :data="tableData()" border style="width: 100%" :max-height="collapseName == '收起' ? 450 : 660" v-loading="tableLoading" @selection-change="handleChangeSelection">
      <template v-slot:empty>
        <div class="no-data">暂无数据</div>
      </template>
      <el-table-column type="selection" width="40" />
      <el-table-column v-for="item in inboundDataColumn" :prop="item.prop" :min-width="item.minWidth" :width="item.width"
        :max-width="item.maxWidth" :label="item.label">
        <!-- <template v-if="true" v-slot:default="scope">
          <div v-if="item.prop == 'orderType'">
            <el-tag v-if="scope.row[item.prop] == 0" type="success">采购入库</el-tag>
            <el-tag v-else-if="scope.row[item.prop] == 1" type="info">借货入库</el-tag>
          </div>
          <span v-else>{{ scope.row[item.prop] }}</span>
        </template> -->
      </el-table-column>
      <el-table-column label="操作" align="center" width="80" fixed="right">
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination" style="float: right; margin-top: 15px;">
      <el-pagination v-model:current-page="data.page" v-model:page-size="data.limit"
        layout="prev, pager, next ,total,sizes" v-model:total="data.total" @current-change="handleCurrentChange"
        @size-change="handleSizeChange" />
    </div>
  </div>

  <el-dialog v-model="dialogFormVisible" title="Shipping address" width="500">
    <el-input  v-model="remark" type="textarea" placeholder="请输入内容"/>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="creatJadeList">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { defineComponent, reactive, toRefs, ref, computed } from "vue";
import '@/mock/inbound.js'
import { onMounted, onBeforeMount } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { createAdjustOrder, getJadeDetail } from '@/api/inbound/inbound'
import { getWarehouseListV2 } from '@/api/setting/setting';
import { getSupplierList } from "@/api/user/user"
import { List } from '@element-plus/icons-vue';
import { useRoute, useRouter } from "vue-router"
import { useStore } from 'vuex';
export default defineComponent({
  name: "HomeView",
  components: {
    List
  },
  setup() {
    const route = useRoute()
    const router = useRouter()
    const store = useStore()

    const dialogFormVisible = ref(false)// 备注对话框弹出
    const multiple = ref(true)// 非多个禁用
    const jadeListForm = ref([]);// 每次添加的调整单列表
    const inputValue = ref()// 输入货品条码
    const isFormVisible = ref(false)// 控制表格显示
    const activeNames = ref(false)
    const rowDetails = ref({})
    const drawer = ref(false)
    const isIndeterminate = ref(false)
    const checkAll = ref(true)// 显示设置是否全选
    const searchForm = reactive({  //入库查询表单数据
      barcode: "",
      name: "",
      costPrice: 0,
      tagPrice: 0,
      marketPrice: 0,
      warehouseId: 0,
      warehouseName: "",
      storageId: 0,
      storageName: "",
      oriNum: 0,
      newNum: 0,
      imageId: 0
    })
    const inboundJadeData = ref([])
    const selectedFilters = ref([])
    const selectedRows = ref([])//已勾选记录
    const inboundDataColumn = ref([])//表头数据
    const adjustedNum = ref(searchForm.newNum - searchForm.oriNum);
    const remark = ref("")
    const storageNameList = ref([])
    const warehouseList = ref([])
    const tableFilter = ref([
      { label: '条码号', prop: 'barcode', width: '100', isdisabled: true, isSelected: true },
      { label: '货物名', prop: 'name', width: '120', isdisabled: true, isSelected: true },
      { label: '成本价', prop: 'costPrice', width: '100', isdisabled: true, isSelected: true },
      { label: '标签价', prop: 'tagPrice', width: '100', isdisabled: true, isSelected: true },
      { label: '市场价', prop: 'marketPrice', width: '200', isdisabled: true, isSelected: true },
      { label: '仓库名', prop: 'warehouseName', width: '100', isdisabled: true, isSelected: true },
      { label: '仓位id', prop: 'storageId', width: '200', isdisabled: true, isSelected: true },
      { label: '仓位名', prop: 'storageName', width: '200', isdisabled: true, isSelected: true },
      { label: '原库存', prop: 'oriNum', width: '200', isdisabled: true, isSelected: true },
      { label: '修改后库存', prop: 'newNum', width: '200', isdisabled: true, isSelected: true },
    ])

    const collapseName = ref('展开');

    //分页处理
    const state = reactive({//表格用到的参数
      data: {
        page: 1,
        limit: 10,
        total: inboundJadeData.value.length,
      }
    });

    // loading
    const tableLoading = ref(true)


    const selectListFullfiled = (val) => {// select下拉列表的数组或字符串处理
      if(Array.isArray(val.warehouseName)){
        val.warehouseName.forEach(item => {
          warehouseList.value.push(item)
        })
      }else{
        warehouseList.value.push(val.warehouseName)
      }
      if(Array.isArray(val.storageName)){
        val.storageName.forEach(item => {
          storageNameList.value.push(item)
        })
      }else{
        storageNameList.value.push(val.storageName)
      }
    }
    // 更新调整数
    const updateAdjustedNum = () => {
      adjustedNum.value = searchForm.newNum - searchForm.oriNum;
    };

    const handleClick = (value) => {// 点击查询展开
      const params = {
        barcode: value
      }
      getJadeDetail(params).then((res) => {
        if(res.code !== 200){// 返回数据失败则报错提示，这样写的原因是在请求拦截那里已经对错误信息处理了所以不能用catch
          ElMessage({
            type: 'info',
            message: '无效货品码输入',
          })
          return
        }
        selectListFullfiled(res.data)
        isFormVisible.value = true
        // 更新 searchForm 数据
        Object.assign(searchForm, res.data);
        searchForm.newNum = searchForm.oriNum // 刚开始需要新数据等于旧数据
        console.log("getJadeDetail:",res)
        console.log("searchForm:",searchForm)
      })
      console.log("value:",value)
    }
    const tableData = () => {
      // console.log("inboundJadeData:",inboundJadeData)
      return jadeListForm.value
    };
    const handleCurrentChange = (e) => {//改变页码
      state.data.page = e;
      handleGetInboundOrderList(e, state.data.limit)
    };
    const handleSizeChange = (e) => {//改变页数限制
      state.data.limit = e;
      handleGetInboundOrderList(state.data.page, e)
    };

    const handleGetInboundOrderList = (page, limit) => {//获取入库单列表
      tableLoading.value = true
      const params = {
        pageNum: page,
        pageSize: limit
      }
      // getAuditOrderDetail(params).then((res) => {
      //   console.log("getAuditOrderDetail:",res)
      //   inboundJadeData.value = res.data
      //   // state.data.total = res.data.length
      //   tableLoading.value = false
      // })
      tableLoading.value = false
    }
    const handleCheckAllChange = (val) => {//全选按钮
      inboundDataColumn.value = []
      selectedFilters.value = []
      isIndeterminate.value = false;
      if (val) {
        tableFilter.value.forEach(item => {
          item.isSelected = val
          inboundDataColumn.value.push(item)
          selectedFilters.value.push(item.label)
        })
      }
    }
    const handleCheckChange = (val) => {//勾选列
      let temp = []
      tableFilter.value.forEach(item_t => {
        selectedFilters.value.forEach(item_s => {
          if (item_t.label == item_s) {
            temp.push(item_t)
          }
        })
      })
      if (temp.length < tableFilter.value.length && temp.length > 0) {
        isIndeterminate.value = true
      } else {
        isIndeterminate.value = false
      }
      inboundDataColumn.value = temp
      selectedFilters.value = inboundDataColumn.value.map(item => item.label)
    }

    // onBeforeMount(() => {
    //   getSupplierList().then((res) => {
    //     storageNameList.value = res.rows
    //   })
    //   getWarehouseListV2().then((res) => {
    //     warehouseList.value = res
    //   })
    // })

    onMounted(() => {
      handleGetInboundOrderList(state.data.page, state.data.limit)
      tableFilter.value.forEach(function (item, index) {
        if (item.isSelected) {
          selectedFilters.value.push(item.label)
          inboundDataColumn.value.push(item)
        }
      })
    })

    const printSelectedRows = () => {//打印入库单货品明细
      if (selectedRows.value.length == 0) {
        ElMessage.warning('请选择要打印的记录')
      } else {
        const printWindow = window.open('', '_blank');
        let content = `<html><head><title>打印</title></head><body>`
        content += `<h1>入库货品明细</h1>`
        content += `<table style="border-collapse: collapse; width: 100%;">`;
        content += `<tr>
            <th style="border: 1px solid black; padding: 8px;">入库单单号</th>
            <th style="border: 1px solid black; padding: 8px;">数量</th>
            <th style="border: 1px solid black; padding: 8px;">入库时间</th>
            <th style="border: 1px solid black; padding: 8px;">供应商</th>
            <th style="border: 1px solid black; padding: 8px;">入库仓库</th>
            <th style="border: 1px solid black; padding: 8px;">入库人员</th>
          </tr>`;
        selectedRows.value.forEach(row => {
          content += `<tr>
              <td style="border: 1px solid black; padding: 8px;">${row.orderCode}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.jadeQuantity}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.createTime}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.supplierName}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.warehouseName}</td>
              <td style="border: 1px solid black; padding: 8px;">${row.createBy}</td>
            </tr>`;
        });
        content += `</table></body></html>`;
        printWindow.document.open();
        printWindow.document.write(content);
        printWindow.print()
        printWindow.onload = () => {
          printWindow.print();
          printWindow.close();
        };
        selectedRows.value = []
      }
    }

    const mergeOrder = () => {

    }

    const creatJadeList = () => {
      dialogFormVisible.value = false
      const params = {
        checkOrderId: null,
        jadeList: selectedRows.value,
        remark: remark.value,
      }
      createAdjustOrder(params).then((res) => {
        console.log(res)
      })
      console.log("selectedRows:",selectedRows)
      console.log("jadeList:",params)
    }

    const onSearch = () => {
      // 检查是否存在相同的 barcode
      const exists = jadeListForm.value.some(item => item.barcode === searchForm.barcode);
      if (exists) {
        ElMessage.error('条码重复，不能添加'); // 显示错误消息
        return;
      }
      const newEntry = { ...searchForm };
      jadeListForm.value.push(newEntry);
      ElMessage.success('添加成功'); // 显示成功消息
      isFormVisible.value = false
      console.log("jadeListForm:",jadeListForm)
      // getInJadeList(params).then((res) => {
      //   inboundJadeData.value = res.data
      //   state.data.total = res.data.length
      //   tableLoading.value = false
      // })
    }

    const openDetails = (row) => { //删除仓位
      drawer.value = true
      rowDetails.value = row
    }
    const printTag = (row) => { //打印标签
      drawer.value = true
      rowDetails.value = row
    }
    const handleChangeSelection = (selection) => {//已勾选的记录
      multiple.value = !selection.length
      selectedRows.value = selection
      // console.log(selectedRows)
    }
    /** 删除按钮操作 */
    const handleDelete = (row) => {
      const index = jadeListForm.value.indexOf(row);
      ElMessageBox.confirm(
        'proxy will permanently delete the file. Continue?',
        'Warning',
        {
          confirmButtonText: 'OK',
          cancelButtonText: 'Cancel',
          type: 'warning',
        }
      )
      .then(() => {
        jadeListForm.value.splice(index, 1);// 数组中删除该行
        ElMessage({
          type: 'success',
          message: 'Delete completed',
        })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: 'Delete canceled',
        })
      })
    }
    const onReset=()=>{
      searchForm.jadeCode=searchForm.orderCode=searchForm.storageName=searchForm.warehouseName=''
    }

    return {
      inboundJadeData,jadeListForm,multiple,remark,dialogFormVisible,
      searchForm, rowDetails, drawer, activeNames,isFormVisible,
      collapseName, warehouseList, storageNameList,inputValue,adjustedNum,
      inboundDataColumn, selectedFilters, tableFilter, checkAll, isIndeterminate,
      handleClick,selectListFullfiled,updateAdjustedNum,creatJadeList,handleDelete,
      tableData, mergeOrder, openDetails, printTag, printSelectedRows, handleChangeSelection,
      handleCurrentChange, handleSizeChange, handleCheckAllChange, handleCheckChange,
      handleGetInboundOrderList, onSearch,onReset,tableLoading,
      ...toRefs(state),
    };
  },
});


</script>
    #F8F8F8
    
<style rel="stylesheet/scss" lang="scss" scoped>
.input-container {
  display: flex;
  align-items: left;
  margin: 10px 0;
  .label {
    margin-right: 10px;
    font-size:x-small;
    color: #0066cc;
    margin: 10px;
    padding: 8px;
    background-color: #d9ecff;
  }

  .input-box {
    margin-right: 10px;
    width: 220px;
    padding: 8px;
  }

  .submit-button {
    padding: 5px 10px;
  }
}



.front {
  background-color: #FFF;
  padding: 10px;
  .front-text{ 
    padding: 3px;
    font-size:x-small;
    color: #0066cc;
    margin: 10px;
    background-color: #d9ecff;
  }
  .front-input {
    width: 320px;
  }
}

.center {
  margin-top: 10px;
  // border-top: 1px solid var(--el-border-color);
  // border-bottom: 1px solid var(--el-border-color);
}

.tail {
  background-color: #FFF;
  margin-top: 10px;
  padding: 10px;
}

.tail-action {
  display: flex;
  margin-bottom: 10px;
}


.center .center-data {
  height: 30px;
  width: 150px;
  border: 1px solid;
  border-radius: 10px;
  margin: 10px;
  text-align: center;
  font-size: 20px;
  background-color: #72f6ff;
}

.el-table {
  .el-button {
    margin-left: 0px; //调整按钮不对齐
  }
}
</style>
    